package pri.zjy.interview;

import pri.zjy.tree.model.TreeNode;

import java.util.*;

/**
 * @author zhangjy
 * @description
 * @date 2025/5/29 16:25
 */
public class Test {

    /**
     *          1
     *      2        3
     *     4   5
     */

    public static void main(String[] args) {
        TreeNode five = new TreeNode(5);
        TreeNode four = new TreeNode(4);
        TreeNode two = new TreeNode(2, four, five);
        TreeNode three = new TreeNode(3);
        TreeNode one = new TreeNode(1,  two, three);

        getRight(one).forEach(System.out::println);
    }

    public static List<Integer> getRight(TreeNode root) {
        // 记录每层最后一个节点
        if (root == null) return null;

        List<Integer> ans = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            // 本层节点个数
            int curLevelSize = queue.size();
            for (int i = 0; i < curLevelSize; i++) {
                TreeNode pop = queue.poll();
                // 记录下层节点 入栈
                if (pop.left != null) queue.offer(pop.left);
                if (pop.right != null) queue.offer(pop.right);

                // 本层最后一个节点记录到ans
                if (i == curLevelSize - 1) ans.add(pop.val);
            }
        }

        return ans;
    }

}
